import json
import framework.utils.basic as basic

folder = 'db/'

key_id = basic.key_id


def write(db_id, objects):
    #data = {'total': len(objects), 'rows': objects}

    for obj in objects:
        if key_id in obj.keys():
            del obj[key_id]

    f = open(folder + db_id, 'w')
    f.write(json.dumps(objects))
    f.close()


def __read_json(db_id):
    f = open(folder + db_id, 'r')
    json_str = f.read()
    f.close()
    return json_str


def read(db_id):
    """

    :rtype: object
    """
    data = json.loads(__read_json(db_id))

    if not isinstance(data, list):
        if 'rows' in data.keys():
            data = data['rows']

    i = 0
    for obj in data:
        obj[key_id] = i
        i = i + 1

    return data


def read_json(db_id):
    objects = read(db_id)

    data = {'total': len(objects), 'rows': objects}

    return json.dumps(data)


def read_page_json(db_id, page, rows):
    data = read(db_id)
    objects = data[(page - 1) * rows:page * rows- 1]
    return json.dumps({'total': len(data), 'rows': objects})


def sync(db_id, objects):
    key = key_id
    data = read(db_id)
    maps = {}
    line = 0
    for obj in data:
        maps[obj[key]] = line
        line = line + 1  # print(obj[key], line)

    for obj in objects:
        obj_key = obj[key]
        if obj_key in maps.keys():
            line = maps[obj_key]
            data[line] = obj  # print('change ', line)
        else:
            data.append(obj)
    write(db_id, data)



